package com.qkst.website.common.utils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ClassUtil {
	
	public static Object getEntrty(Class clazz,Map<String,String> map){
		try {
			Object obj = clazz.newInstance();
			Method[] methods = clazz.getMethods();
			for(String str : map.keySet()){
				for(Method method : methods){
					if(method.getName().trim().equals(toMethedName(str))){
						Class clz[] = method.getParameterTypes();
						if(clz.length == 1){
							setValue(obj, clz[0], method, map.get(str));
						}
					}
				}
			}
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static String toMethedName(String str){ 
		if(str != null && !str.trim().equals("") && str.length() >= 1){
			StringBuffer sb = new StringBuffer();
			sb.append("set");
			sb.append(str.substring(0,1).toUpperCase());
			if(str.length() > 1){
				sb.append(str.substring(1));
			}
			return sb.toString();
		}
		return null;
	}
	
	private static void setValue(Object obj,Class clazz,Method method,Object str)throws Exception{
		if(clazz.equals(Integer.TYPE)){
		if(str == null || str.toString() == null || str.toString().equals(""))
			str = "0";
			method.invoke(obj, StringUtils.stringToInt(str.toString()));
		}else if(clazz.equals(Float.TYPE)){
			if(str == null || str.toString() == null || str.toString().equals(""))
				str = "0";
			method.invoke(obj, StringUtils.stringToFloat(str.toString()));
		}else if(clazz.equals(Double.TYPE)){
			if(str == null || str.toString() == null || str.toString().equals(""))
			str = "0";
			method.invoke(obj, StringUtils.stringToDouble(str.toString()));
		}else if(clazz.equals(Character.TYPE)){
			if(str == null || str.toString() == null || str.toString().equals(""))
			str = "0";
			method.invoke(obj, StringUtils.stringToChar(str.toString()));
		}else if(clazz.equals(Long.TYPE)){
			if(str == null || str.toString() == null || str.toString().equals(""))
			str = "0";
			method.invoke(obj, StringUtils.stringToLong(str.toString()));
		}else if(clazz.equals(String.class)){
			method.invoke(obj, str);
		}
	}
	
	public static Map<String,String> getMethodToMap(Class clazz) throws Exception{
		Map<String,String> map = new HashMap<String, String>();
		Object obj = clazz.newInstance();
		Method[] methods = clazz.getMethods();
		for(Method method : methods){
			if(method.getName().length() > 3 && method.getName().substring(0,3).contains("get")){
				Class clz[] = method.getParameterTypes();
				if(clz.length == 0){
					map.put(method.getName().substring(3,method.getName().length()).toLowerCase(),method.invoke(obj, null).toString());
				}
			}
		}
		return map;
	}
}
